<template>
  <el-dialog :visible.sync="visible" :title="dialogTitle" append-to-body>
    <el-form :model="formData" :rules="formRules" ref="formRef" label-width="100px">
      <el-form-item label="角色名称" prop="name">
        <el-input v-model="formData.name"></el-input>
      </el-form-item>
      <el-form-item label="角色类型" prop="type">
        <el-radio-group v-model="formData.type">
          <el-radio label="user">用户</el-radio>
          <el-radio label="admin">管理员</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input type="textarea" v-model="formData.remark"></el-input>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="cancel">取消</el-button>
      <el-button type="primary" @click="submit">确定</el-button>
    </div>
  </el-dialog>
</template>

<script>
export default {
  name: 'RoleFormDialog',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    role: {
      type: Object,
      default: () => ({})
    },
    isEdit: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      formData: {
        id: null,
        name: '',
        type: 'user',
        remark: ''
      },
      formRules: {
        name: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ],
        type: [
          { required: true, message: '请选择角色类型', trigger: 'change' }
        ]
      }
    }
  },
  computed: {
    dialogTitle() {
      return this.isEdit ? '编辑角色' : '新增角色'
    }
  },
  watch: {
    visible(val) {
      if (val) {
        this.resetForm()
      }
    },
    role: {
      handler(val) {
        this.resetForm()
      },
      deep: true
    }
  },
  methods: {
    resetForm() {
      this.formData = this.isEdit ? { ...this.role } : { id: null, name: '', type: 'user', remark: '' }
    },
    submit() {
      this.$refs.formRef.validate(valid => {
        if (valid) {
          this.$emit('save', { ...this.formData })
        } else {
          this.$message({ type: 'error', message: '表单验证失败，请检查' })
          return false
        }
      })
    },
    cancel() {
      this.$emit('close')
    }
  }
}
</script>
